package www.bwsensing.com.common.netty;

import com.alibaba.cola.exception.Assert;
import lombok.Data;
import www.bwsensing.com.common.cache.RedisService;
import www.bwsensing.com.common.mqtt.MqttPushClient;
import www.bwsensing.com.common.netty.handler.NettyUdpServerHandler;
import www.bwsensing.com.common.netty.initializer.NettyUdpInitializer;
import www.bwsensing.com.service.collection.database.dataobject.ServiceData;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务初始化工厂
 * @author macos-zyj
 */
@Data
public class NettyUdpServerFactory {
    private static final Map<Integer, NettyUdpServerImpl> NETTY_UDP_SERVICE = new ConcurrentHashMap<>();

    public static NettyUdpServerImpl getNettyServer(ServiceData serviceData,
                                                    RedisService redisService, MqttPushClient mqttPushClient){
        Assert.notNull(serviceData, "配置信息不能为空!");
        int listenPort = Integer.parseInt(serviceData.getServiceValue());
        if (null != NETTY_UDP_SERVICE.get(listenPort)) {
            return NETTY_UDP_SERVICE.get(listenPort);
        }  else {
            NettyUdpServerHandler serverHandler = new NettyUdpServerHandler(serviceData, redisService, mqttPushClient);
            NettyUdpInitializer udpInitializer = new NettyUdpInitializer(serverHandler);
            NettyUdpServerImpl runServer = new NettyUdpServerImpl(listenPort,udpInitializer);
            NETTY_UDP_SERVICE.put(listenPort,runServer);
            return runServer;
        }
    }
}
